
layui.define(['layer','config'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var config = layui.config;

    var login = {
        headers:{
            Authorization:"Basic Zm9udDoxMjM0NTY="
        },
        loginSuccess:function(data){
            layer.closeAll('loading');
            if(data &&  data.access_token){
                config.putToken(data.access_token);
                console.log(data.user)
                config.putUser(data.user);
                layer.msg('登录成功', {icon: 1, time: 100}, function () {
                    location.replace('./index.html');
                });
            }else if(data && data.msg){
                layer.msg(data.msg, {icon: 2, time: 5000});
                $('.login-captcha').click();
            }
            console.log(data);
        },
        loginError:function(data){
            layer.closeAll('loading');
            if(data.status == 428){
                layer.msg("验证码错误",{icon: 2, time: 1500})
                $('.login-captcha').click();
            }else{
                layer.msg("系统异常",{icon: 2, time: 1500})
                $('.login-captcha').click();
            }
        },
        codeAutoLogin:function(){
            var url =location.href;
            var i1 = url.indexOf("code=");
            if(i1 == -1){
                return;
            }
            var i2 = url.indexOf("&",i1);
            var code = url.substring(i1+5,i2);
             i1 = url.indexOf("state=");
            if(i1 == -1){
                return;
            }
            i2 = url.indexOf("&",i1);
            if(i2==-1){
                var state = url.substring(i1+6);
            }else{
                var state = url.substring(i1+6,i2);
            }
            layer.load(2);
            $.ajax({
                url:"auth/login/"+state,
                type:"post",
                data:{
                    code:code,
                    scope:"font"
                },
                headers:login.headers,
                dataType:"json",
                success:login.loginSuccess,
                error:login.loginError
            })
        },

        guid:function () {
            function S4() {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            }
            var uuid =  (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
            $("#uuid").val(uuid);
            return uuid;
        }
    }

    exports('login', login);
});
